package com.orharlan.carassistant.gui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.orharlan.carassistant.R;
import com.orharlan.carassistant.datamodel.Datamodel;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SettingsEMailActivity extends Activity
{
	public static Datamodel data;

	private EditText mailAddressEt;
	private TextView titelTv;
	private Button saveEmailBt;
	private Button deleteEmailBt;

	@Override
	protected void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_settingsemail );

		// Refer the Edittext field for the mail address and all other else
		mailAddressEt = (EditText) findViewById( R.id.mailAddressEt );
		titelTv = (TextView) findViewById( R.id.titelTv );
		saveEmailBt = (Button) findViewById( R.id.saveEmailBt );
		deleteEmailBt = (Button) findViewById( R.id.deleteEmailBt );

		// Set fonts
		Typeface tf = Typeface.createFromAsset( getAssets( ), "fonts/myFont.ttf" );
		mailAddressEt.setTypeface( tf );
		titelTv.setTypeface( tf );
		saveEmailBt.setTypeface( tf );
		deleteEmailBt.setTypeface( tf );

		// Call Datamodel
		data = Datamodel.singleton( );

		// Set MailAdress, if the value not default
		if( !data.getMailAddress( ).equals( "" ) )
		{
			mailAddressEt.setText( data.getMailAddress( ) );
		}
	}

	// ///////////////////
	// ON Click Listerner
	public void saveEmailBtListener( View v )
	{
		// Check if the entered MailAdress is in valid format
		String email = mailAddressEt.getText( ).toString( );
		if( isEmailValid( email ) )
		{
			// Save it to the datamodel
			data.setMailAddress( email );
			MainActivity.showShortToast( this, getString( R.string.toastMailSaved ) );
		}
		else
		{
			// Inform the user about a not valid mail format
			MainActivity.showLongToast( this, getString( R.string.toastWrongMailFormat ) );
		}
	}

	public void deleteEmailBtListener( View v )
	{
		// Set mail address to the default value
		data.setMailAddress( "" );
		mailAddressEt.setText( "" );
		mailAddressEt.setHint( getString( R.string.emaildefaultValue ) );
	}

	/**
	 * method is used for checking valid email id format.
	 * 
	 * @param email
	 * @return boolean true for valid false for invalid
	 */
	public static boolean isEmailValid( String email )
	{
		boolean isValid = false;

		String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
		CharSequence inputStr = email;

		Pattern pattern = Pattern.compile( expression, Pattern.CASE_INSENSITIVE );
		Matcher matcher = pattern.matcher( inputStr );
		if( matcher.matches( ) )
		{
			isValid = true;
		}
		return isValid;
	}
}
